package domain;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLHandshakeException;

public class SslInvoker {

	private boolean isSucces;
	private String shortMessage;
	private String longMessage;
	
	public SslInvoker() {
	}

	public void doTest(SslObject sslObject) {
		shortMessage = null;
		longMessage = null;
		
		isSucces = createConnection(sslObject);
	}
	
	public boolean isSucces() {
		return isSucces;
	}

	public String getShortMessage() {
		return shortMessage;
	}	
	
	public String getLongMessage() {
		return longMessage;
	}
	
	private boolean createConnection(SslObject sslObject)  {
		
		try {
			
			URL url = new URL(sslObject.getUrl());
			HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
			con.connect();
			
			Certificate[] certs = con.getServerCertificates();
			
			if (certs[0].getType().equalsIgnoreCase("x.509")) {
				X509Certificate X509cert = (X509Certificate) certs[0];
				sslObject.setExpiry(X509cert.getNotAfter());
			}
			
			for (Certificate c : certs)
			{
				X509Certificate X509cert = (X509Certificate) c;
				
				longMessage = longMessage + X509cert.getSigAlgName();
						
			}
			
			con.disconnect();

		} catch (SSLHandshakeException e) {
			//e.printStackTrace();	
			shortMessage = e.getMessage();
			return false;
		} catch (MalformedURLException e) {
			//e.printStackTrace();
			shortMessage = e.getMessage();
			return false;
		} catch (IOException e) {
			//e.printStackTrace();	
			shortMessage = e.getMessage();
			return false;
		}
		
		return true;
	
	}
	
}
